home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Clearing the keyboard buffer in ANSI C
- Date: 28 Jan 1996 15:13:12 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4egvu8INN7g3@keats.ugrad.cs.ubc.ca>
- References: <tfiedler-2801961347210001@205.217.163.224>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <tfiedler-2801961347210001@205.217.163.224>,
- Todd A. Fiedler <tfiedler@muscanet.com> wrote:
- >Help.
- >
- >I am a newbie to C and I can't figure out how to clear the keyboard buffer.
- >
- >I am writing a program that runs from the console and asks for user input.
- >Anyway, I cannot seem to get the last newline character out of the stream
- >before my next fscanf or fgets. I have tried fflush() to no avail. I have
- >even tried placing "%*s" in my fscanf string to capture the errant
- >newline. Still
- >won't work.
-
- The standard C library knows no such thing as a keyboard. It originated on UNIX
- systems as a programming convenience. However, the terminal driver you are
- interacting with has its own line buffering that works independently of the
- standard I/O library. fflush() only clears the standard library's buffers, not
- the buffers that the underlying OS associates with your keyboard, terminal or
- what have you.
-
- The more you think about it, the less it has to do with C.
-
- The precise way to do this varies with the OS. If you are on a UNIX system, you
- can put the terminal in a special raw mode whereby line buffering is disabled,
- and each call to read() will return as soon as there are characters ready. You
- can then use select() with a time-out of zero (or a small value) to poll the
- terminal and keep extracting characters from it until select() polls negative.
- Without enabling the terminal raw mode, this won't do anything, since in
- canonical input mode, the terminal driver will not report the presence of any
- input until the user hits "Enter".
-
- If all you want is to flush that "Enter", then you can get away without
- massaging the terminal mode. HOwever, you will not be able to flush the partial
- line that the user has typed in, just everything up to the most recent newline.
- That may be good enough if all you are doing is line-buffered input.
-
- >Any suggestions, help or comments would be *greatly* appreciated.
-
- Go to a newsgroup that discusses programming details for the operating system
- that you use.
-
- --
-
-